//
//  QWRegisterController.m
//  qwm
//
//  Created by kevin on 2023/3/26.
//

#import "QWRegisterController.h"
#import "QWRegCell.h"
#import "QWLoginButtonCell.h"
#import "QWChooseCell.h"
#import "QWRegPassTipsView.h"

@interface QWRegisterController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *menusArr;
@property (nonatomic, strong) NSArray *doctorArr;
@property (nonatomic, strong) NSDictionary *userTypedic;
@property (nonatomic, copy) NSString *userType; //用户类型 doctor, assistant, patient
@end

@implementation QWRegisterController

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    [self loadInfo];
    [self tableView];
}
- (void)loadInfo{
    self.menusArr = [NSMutableArray arrayWithArray:@[
        @{
            @"name":@"姓名",
            @"textFieldPal":@"请填写真实姓名",
        },
        @{
            @"name":@"手机号",
            @"textFieldPal":@"请输入手机号",
        },
        @{
            @"name":@"密码",
            @"textFieldPal":@"请输入密码",
        },
        @{
            @"name":@"确认密码",
            @"textFieldPal":@"请再次输入密码",
        },
        @{
            @"name":@"用户类型",
            @"textFieldPal":@"请再次输入密码",
        }
    ]];
    
    self.doctorArr = @[
        @{
            @"name":@"医院名称",
            @"textFieldPal":@"请输入医院名称",
        },
        @{
            @"name":@"科室名称",
            @"textFieldPal":@"请输入可是名称",
        },
        @{
            @"name":@"职称",
            @"textFieldPal":@"请输入职称",
        }
    ];
    
    self.userTypedic = @{
        @"assistant":@"医疗专员",
        @"doctor":@"医生",
        @"patient":@"患者",
    };
    _userType = self.userTypedic[@"patient"]; //默认患者
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 400;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedSectionFooterHeight=0;
        _tableView.estimatedSectionHeaderHeight=0;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.showsHorizontalScrollIndicator=NO;
        
        _tableView.delegate =self;
        _tableView.dataSource =self;
        
        [_tableView registerNib:[UINib nibWithNibName:@"QWRegCell" bundle:nil] forCellReuseIdentifier:@"QWRegCell"];
        [_tableView registerClass:[QWChooseCell class] forCellReuseIdentifier:@"QWChooseCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"QWForRegCell" bundle:nil] forCellReuseIdentifier:@"QWForRegCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"QWLoginButtonCell" bundle:nil] forCellReuseIdentifier:@"QWLoginButtonCell"];
        
        _tableView.backgroundColor=Color_TableView_Gray;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;

        
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        
    }
    return _tableView;
}

#pragma mark- UITableViewDelegate,UITableViewDataSource
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return section==0 ? 20.0 : 0.0000001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return section==0 ? 50 : 0.0000001;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section==0 ? self.menusArr.count: 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(indexPath.section == 0){
       
        NSDictionary *dic =self.menusArr[indexPath.row];
        NSString *nameStr = dic[@"name"];
        
        if([nameStr isEqualToString:@"用户类型"]){
            QWChooseCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWChooseCell"];
            cell.type = self.userType;
            return cell;
        }else{
            QWRegCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWRegCell"];
            cell.textField.tag = 1000+indexPath.row+1;
            cell.nameLabel.text = dic[@"name"];
            cell.textField.placeholder = dic[@"textFieldPal"];
            cell.textField.secureTextEntry = [dic[@"name"] isEqualToString:@"密码"] || [dic[@"name"] isEqualToString:@"确认密码"];
            cell.textField.keyboardType = [dic[@"name"] isEqualToString:@"手机号"] ?UIKeyboardTypeNumberPad:UIKeyboardTypeDefault;
            return cell;
        }
    }else{
        QWLoginButtonCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWLoginButtonCell"];
        [cell.loginButton setTitle:@"注册" forState:UIControlStateNormal];
        cell.loginClickBlock = ^{
            [self regist];
        };
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 0){
        NSDictionary *dic =self.menusArr[indexPath.row];
        if([dic[@"name"] isEqualToString:@"用户类型"]){
            [self showUserTypeAlert];
        }
    }
    [self.view endEditing:YES];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if(section == 0){
        QWRegPassTipsView *view = [[QWRegPassTipsView alloc]init];
        return view;
    }else{
        return  [UIView new];
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    [self.view endEditing:YES];
}

#pragma mark - 用户类型选择弹框
- (void)showUserTypeAlert{
    //用户类型 doctor, assistant, patient
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    for (NSString *value in self.userTypedic.allValues) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:value style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if([self.userType isEqualToString:value]) return;
            self.userType = value;
            if([value isEqualToString:@"医生"]){
                [self.menusArr addObjectsFromArray:self.doctorArr];
            }else{
                [self.menusArr removeObjectsInArray:self.doctorArr];
            }
            [self.tableView reloadData];
        }];
    //    [action setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
        [alertController addAction:action];
    }
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
//    [cancelAction  setValue:[UIColor redColor] forKey:@"_titleTextColor"];
    [alertController addAction:cancelAction];
    alertController.modalPresentationStyle = 0;
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 注册请求
- (void)regist{
    UITextField *nameField =(UITextField *)[_tableView viewWithTag:1000+1];
    UITextField *phoneField =(UITextField *)[_tableView viewWithTag:1000+2];
    UITextField *passwordField =(UITextField *)[_tableView viewWithTag:1000+3];
    UITextField *password2Field =(UITextField *)[_tableView viewWithTag:1000+4];
    UITextField *hospitalField =(UITextField *)[_tableView viewWithTag:1000+6];
    UITextField *departmentField =(UITextField *)[_tableView viewWithTag:1000+7];
    UITextField *levelField =(UITextField *)[_tableView viewWithTag:1000+8];

    NSString * name = nameField.text;
    NSString * phone = phoneField.text;
    NSString * pwd1 = [NSString stringWithFormat:@"%@",passwordField.text];
    NSString * pwd2 = [NSString stringWithFormat:@"%@",password2Field.text];
    NSString * hospital = hospitalField.text;
    NSString * department = departmentField.text;
    NSString * level = levelField.text;

    if (IsStringEmpty(name)) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"姓名不能为空。"];
        return;
    }
    if (phone.length != 11) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"手机号不能为空。"];
        return;
    }

    if (pwd1.length < 6 || pwd2.length < 6) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"密码格式有误，请重新输入。"];
        return;
    }
    if (![pwd1 isEqualToString: pwd2]) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"两次输入的密码不一致，请重新输入。"];
        return;
    }

    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:name forKey:@"name"];
    [dic setValue:phone forKey:@"loginName"];
    [dic setValue:pwd1 forKey:@"password"];

    //    doctor, assistant, patient
    [self.userTypedic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if ([obj isEqualToString: self.userType]) {
            [dic setValue:key forKey:@"userType"];
        }
    }];
    
    if(!IsStringEmpty(hospital))[dic setValue:hospital forKey:@"company_id"];
    if(!IsStringEmpty(department))[dic setValue:department forKey:@"office_id"];
    if(!IsStringEmpty(level))[dic setValue:level forKey:@"level"];

    [SWHUDUtil showHudViewInSuperView:self.view withMessage:@"请等待"];
    HXPostRequest * request = [[HXPostRequest alloc] initWithRequestUrl:URL_register argument:dic];
    [request startWithCompletionBlockWithSuccess:^(__kindof HXRequest * _Nonnull request, NSDictionary * _Nonnull result, BOOL success) {
        if ([result[@"code"] integerValue] == 0) {
            NSString *msg = result[@"msg"];
            [SWHUDUtil hideHudViewWithFailureMessage:msg];
        }else{
            [SWHUDUtil hideHudView];
            if(self.registSuccessBlock) self.registSuccessBlock(phone, pwd1);
            [self.navigationController popViewControllerAnimated:YES];
            
//            [[EMClient sharedClient] registerWithUsername:[AppProfile.qaUserInfo.id lowercaseString] password:@"0000" completion:^(NSString * _Nonnull aUsername, EMError * _Nullable aError) {
//                NSLog(@"1231");
//            }];
        }
    } failure:^(__kindof HXRequest * _Nonnull request, NSString * _Nonnull errorInfo) {
        [SWHUDUtil hideHudView];
    }];

}


@end
